package com.hjm.admin.moule.view.fragment.impl;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.MaterialDialog;
import com.allen.library.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hjm.admin.moule.R;
import com.hjm.admin.moule.db.entity.CollBookBean;
import com.hjm.admin.moule.db.entity.DownloadTaskBean;
import com.hjm.admin.moule.db.helpter.BookRecordHelper;
import com.hjm.admin.moule.db.helpter.CollBookHelper;
import com.hjm.admin.moule.event.DeleteResponseEvent;
import com.hjm.admin.moule.event.DeleteTaskEvent;
import com.hjm.admin.moule.event.DownloadMessage;
import com.hjm.admin.moule.utils.LoadingHelper;
import com.hjm.admin.moule.utils.rxhelper.RxBus;
import com.hjm.admin.moule.utils.rxhelper.RxUtils;
import com.hjm.admin.moule.view.activity.impl.ReadActivity;
import com.hjm.admin.moule.view.adapter.BookShelfAdapter;
import com.hjm.admin.moule.view.base.BaseFragment;
import com.hjm.admin.moule.view.fragment.IBookShelf;
import com.hjm.admin.moule.viewmodel.fragment.VMBookShelf;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class BookShelfFragment extends BaseFragment implements IBookShelf {
    @BindView(R.id.rv_book_shelf)
    RecyclerView mRvBookShelf;
    @BindView(R.id.refresh)
    SmartRefreshLayout mSmartRefreshLayout;
    private BookShelfAdapter mBookAdapter;
    private List<CollBookBean> mAllBooks = new ArrayList<>();
    private VMBookShelf mModel;
    private boolean isCheck;

    public static BookShelfFragment newInstance() {
        return new BookShelfFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mModel = new VMBookShelf(mContext, this);
        return setContentView(container, R.layout.fragment_book_shelf, mModel);
    }


    @Override
    protected void initView() {
        mBookAdapter = new BookShelfAdapter(mAllBooks);
        mRvBookShelf.setLayoutManager(new LinearLayoutManager(mContext));
        mBookAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mRvBookShelf.setAdapter(mBookAdapter);

        mSmartRefreshLayout.setOnRefreshListener(refreshlayout -> {
            mAllBooks.clear();
            mAllBooks.addAll(CollBookHelper.getsInstance().findAllBooks());
            mModel.getBookShelf(CollBookHelper.getsInstance().findAllBooks());
        });
        mBookAdapter.setOnItemClickListener((adapter, view, position) -> {
            CollBookBean collBook = mBookAdapter.getItem(position);
            if (collBook.getIsLocal()) {

                //id 表示本地路径
                String path = collBook.get_id();
                File file = new File(path);
                if (file.exists()) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(ReadActivity.EXTRA_COLL_BOOK, collBook);
                    bundle.putBoolean(ReadActivity.EXTRA_IS_COLLECTED, true);
                    startActivity(ReadActivity.class, bundle);
                } else {
                    new MaterialDialog.Builder(mContext)
                            .title(mContext.getResources().getString(R.string.wy_common_tip))
                            .content("文件不存在，是否删除？")
                            .positiveText(mContext.getResources().getString(R.string.wy_common_sure))
                            .onPositive((dialog, witch) -> deleteBook(collBook, position))
                            .negativeText(mContext.getResources().getString(R.string.wy_common_cancel))
                            .onNegative(((dialog, which) -> dialog.dismiss()))
                            .show();
                }
            } else {
                mModel.setBookInfo(collBook);

            }
        });

        //添加书籍下载任务处理
        Disposable downloadDisp = RxBus.getInstance()
                .toObservable(DownloadMessage.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(event -> {
                    ToastUtils.showToast(event.message);
                });
        addDisposable(downloadDisp);
        Disposable deleteDisp = RxBus.getInstance()
                .toObservable(DeleteResponseEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(event -> {
                    if (event.isDelete) {
                        ProgressDialog progressDialog = new ProgressDialog(mContext);
                        progressDialog.setMessage("正在删除");
                        progressDialog.show();
                        CollBookHelper.getsInstance().removeBookInRx(event.collBook)
                                .compose(RxUtils::toSimpleSingle)
                                .subscribe(aVoid -> {
                                    progressDialog.dismiss();
                                    mAllBooks.clear();
                                    mAllBooks.addAll(CollBookHelper.getsInstance().findAllBooks());
                                    mBookAdapter.notifyDataSetChanged();
                                });
                    } else {
                        AlertDialog tipDialog = new AlertDialog.Builder(mContext)
                                .setTitle("您的任务正在加载")
                                .setMessage("请先暂停任务在进行删除")
                                .setPositiveButton("确定", (dialog, whitch) -> dialog.dismiss())
                                .create();
                        tipDialog.dismiss();
                    }
                });
        addDisposable(deleteDisp);
        mBookAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            openItemDialog(mAllBooks.get(position), position);
            return true;
        });
    }

    private void openItemDialog(CollBookBean bean, int position) {
        String[] menus = getResources().getStringArray(R.array.wy_menu_local_book);
        new MaterialDialog.Builder(mContext)
                .title(bean.getTitle())
                .items(menus)
                .itemsCallback((dialog, itemView, witch, text) -> onItemMenuClick(menus[witch], bean, position)).show();
    }

    private void onItemMenuClick(String menu, CollBookBean bean, int position) {
        switch (menu) {
            case "缓存":
                downloadBook(bean);
                break;
            case "删除":
                deleteBook(bean, position);
                break;
        }

    }

    private void downloadBook(CollBookBean bean) {
        DownloadTaskBean task = new DownloadTaskBean();
        task.setTaskName(bean.getTitle());
        task.setTaskName(bean.get_id());
        task.setBookId(bean.get_id());
        task.setBookChapters(bean.getBookChapters());
        task.setLastChapter(bean.getBookChapters().size());
        RxBus.getInstance().post(task);
    }

    private void deleteBook(CollBookBean collBook, int position) {
        if (collBook.getIsLocal()) {
            new MaterialDialog.Builder(mContext)
                    .title("删除本地书籍")
                    .checkBoxPrompt("同时删除本地文件", false, (buttonView, isChecked) -> isCheck = isChecked)
                    .positiveText(R.string.wy_common_sure)
                    .onPositive((dialog, which) -> {
                        if (isCheck) {
                            LoadingHelper.getInstance().showLoading(mContext);
                            File file = new File(collBook.get_id());
                            if (file.exists()) file.delete();
                            CollBookHelper.getsInstance().removeBookInRx(collBook)
                                    .subscribe(s -> {
                                        ToastUtils.showToast(s);
                                        BookRecordHelper.getsInstance().removeBook(collBook.get_id());
                                        mBookAdapter.remove(position);
                                        LoadingHelper.getInstance().hideLoading();
                                    }, throwable -> {
                                        ToastUtils.showToast("删除失败");
                                        LoadingHelper.getInstance().hideLoading();
                                    });
                        } else {
                            CollBookHelper.getsInstance().removeBookInRx(collBook);
                            BookRecordHelper.getsInstance().removeBook(collBook.get_id());
                            mBookAdapter.remove(position);
                        }
                        mBookAdapter.notifyDataSetChanged();
                    }).negativeText(R.string.wy_common_cancel).onNegative((dialog, which) -> dialog.dismiss());
        } else {
            RxBus.getInstance().post(new DeleteTaskEvent(collBook));
            mModel.deleteBookShelfToServer(collBook);
        }
    }

    @Override
    public void onResume() {
        mAllBooks.clear();
        mAllBooks.addAll(CollBookHelper.getsInstance().findAllBooks());
        mBookAdapter.notifyDataSetChanged();
        mModel.getBookShelf(CollBookHelper.getsInstance().findAllBooks());
        super.onResume();
    }

    @Override
    public void bookShelfInfo(List<CollBookBean> beans) {
        mAllBooks.addAll(beans);
        mBookAdapter.notifyDataSetChanged();
    }

    @Override
    public void bookInfo(CollBookBean bean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(ReadActivity.EXTRA_COLL_BOOK, bean);
        bundle.putBoolean(ReadActivity.EXTRA_IS_COLLECTED, true);
        startActivity(ReadActivity.class, bundle);
    }

    @Override
    public void deleteSuccess() {
        mBookAdapter.notifyDataSetChanged();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void stopLoading() {
        mSmartRefreshLayout.finishRefresh();
    }
}
